# coding:utf-8
from project.decorators import admin_required
from project.auth import auth
from project.auth.forms import *
from project.auth.models import *
from flask import render_template, flash, redirect, request, url_for, abort
from flask.ext.login import login_user, logout_user, login_required, current_user
from contrib.utils.mail_sender import send_email


@auth.route('/login', methods=['get', 'post'])
def login():
    form = LoginForm()
    user = None
    msg = None
    if form.validate_on_submit():
        name = form.username.data
        pwd = form.password.data
        user = User.query.filter_by(username=name).first()
        if user is not None:
            if user.verify_password(pwd):
                login_user(user, form.keep_login.data)
                return redirect(request.args.get('next') or url_for('main.index'))
            else:
                msg = '登录失败，密码错误'
        else:
            msg = '登录失败，没有此账号'
    if msg is not None:
        flash(msg)
    return render_template('auth/login.html', form=form)


@auth.route('/logout')
def logout():
    logout_user()
    flash('您已经退出登录')
    return redirect(url_for('main.index'))


@auth.route('/register', methods=['get', 'post'])
def register():
    form = RegForm()
    user = None
    if form.validate_on_submit():
        user = User(email=form.email.data)
        user.username = form.username.data
        user.password = form.password.data

        db.session.add(user)
        db.session.commit()

        user.create_head_pic()
        login_user(user)
        return redirect(url_for('auth.confrim', token=0))

    return render_template('auth/register.html', form=form)


@auth.route('/confrim/<token>')
@login_required
def confrim(token):
    if current_user.confirmed:
        return redirect(request.args.get('next') or url_for('main.index'))
    if current_user.confirm(token):
        flash('恭喜，您已经完成了邮箱验证')
    else:
        user = current_user
        tk = user.generate_confirmation_token()
        send_email('MyBlog2.0邮箱验证', '确认链接是' + url_for('auth.confrim', token=tk, _external=True),
                   recipients=[user.email])
        flash('验证邮件已经发送至您的邮箱。')
    return render_template('auth/confrim.html')


@auth.before_app_request
def defore_request():
    if current_user.is_authenticated:
        current_user.ping()
        if not current_user.confirmed and request.endpoint[:5] != 'auth.':
            return redirect(url_for('auth.confrim', token=0))



